<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/7/4
 * Time: 10:41
 */

namespace pay\modules\backend\controllers;

use pay\libs\Tools;
use pay\modules\backend\models\SysLog;
use Yii;
use pay\modules\backend\models\CommonApp;
use yii\web\Controller;

class BasicController extends Controller
{
    protected $userInfo;//登录信息
    protected $permissions;//角色权限信息
    protected $permissionApps;

    public function init()
    {
        parent::init();
        /*请求认证中心,获取用户登录信息*/
        // $this->userInfo = 1;
        if(isset(Yii::$app->session->get('loginInfo')->userInfo)){
            $this->userInfo = Yii::$app->session->get('loginInfo')->userInfo;
            $this->permissions = Yii::$app->session->get('loginInfo')->permissions;
            $this->permissionApps = Yii::$app->session->get('loginInfo')->permissionApps;
        };

    }


    public function beforeAction($action)
    {
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        $allow_origin = array(
            'http://10.9.87.25:8080',
            'http://view.horsevision.cn',
            'http://view.raysfly.com',
            'http://yun.horsevision.cn',
            'http://cloud.raysfly.com',
            'http://yun.raysfly.com',
        );
        // P($origin);
        if (in_array($origin, $allow_origin)) {
            header('Access-Control-Allow-Origin:' . $origin);
            header('Access-Control-Allow-Methods:POST,GET');
            header('Access-Control-Allow-Credentials:true');
        }

        $module = $this->module->id;
        $controller = $this->id;
        $action = $this->action->id;
        $router = $module . '=' . $controller . '=' . $action;
        if (parent::beforeAction($action)) {
            if(!empty($this->userInfo)){
                // return true;

                /*验证权限*/
                $pass = false;
                if($this->userInfo['issuper'] == 1 or
                    in_array($router, Yii::$app->params['allowRouter'])){//菜单列表
                    $pass = true;
                }else{
                    foreach($this->permissions as $k => $v){
                        if(isset($this->get['appid'])){
                            if($v['appid'] == $this->get['appid'] and $v['m'] == $module and $v['c'] == $controller and $v['a'] == $action){
                                $pass = true;
                                break;
                            }
                        }else{
                            // echo $v['m'] . '*' . $v['c'] . '*' . $v['a'] . '<br>';
                            // echo $module . '-' . $controller . '-' . $action . '<br>';
                            // echo '----------------<br>';
                            if($v['m'] == $module and $v['c'] == $controller and $v['a'] == $action){
                                $pass = true;
                                break;
                            }
                        }
                    }
                }
                if($pass){
                    return true;
                }else{
                    echo Tools::showRes(10020,'您没有权限');
                    return false;
                }


            };
            return true;
            if(!isset($errno)){
                echo Tools::showRes(10020,'您没有权限');
                return false;
            }
        }
    }




    public function actionOpenApp()
    {
        if (\Yii::$app->request->isPost){
            $post = \Yii::$app->request->post();
            $appCommentModel = new CommonApp();

            if(($appInfo = $appCommentModel->addApp($post)) !== false){
                $this->setSysLog('开通APP实例成功');
                $backInfo = [0, '开通APP实例成功'];//返回信息
                //开通直播间
//                Live::add(time(),$post['app_name'],$appInfo['appid']);
                return $this->showRes($backInfo,['appinfo' => $appInfo]);
            }
        }
        $this->setSysLog('开通APP实例失败');
        return $this->showRes([0, '开通APP实例失败']);

        //http://paycentre.horsevision.cn/index.php?r=

    }


    /**** 通过appId获取app_id
     * @param $appId
     * @return mixed|string
     */
    protected function getAppId($appId)
    {
        $commontInfo = CommonApp::find()->where('appid = :aid',[':aid' => $appId])->asArray()->one();
        if (!empty($commontInfo)){
            return $commontInfo['app_id'];
        }
        return '';
    }


    protected function setSysLog($content)
    {
        $userInfo = Yii::$app->session->get('loginInfo')->userInfo;
        $patams = [
            'SysLog' => [
                'user_id' => $userInfo['admin_id'],
                'username' => $userInfo['username'],
                'login_add' => '',
                'login_ip' => Yii::$app->request->userIP,
                'content' => $content,
                'operate_time' => date("Y-m-d H:i:s"),
            ]
        ];
        $sysModel = new SysLog();
        if ($sysModel->addInfo($patams)){
            return true;
        }else{
            return false;
        }
    }


    /*文件上传*/
    public function actionUploadFile()
    {
        date_default_timezone_set("Asia/Shanghai");//设置时区
        $temp_arr = explode(".", $_FILES['file']['name']);
        $file_ext = array_pop($temp_arr);
        $file_ext = trim($file_ext);
        $file_ext = strtolower($file_ext);
        if($file_ext == 'pem'){
            $filePath = 'files/';
        }else{
            return Tools::showRes(10405,'文件格式有误');
        }
        $filePath .= date('Ymd')."/";
        $fileName = date("Ymd").Tools::generateStr(3).date("His").Tools::generateStr(3).".".$file_ext;
        // P($_FILES, false);
        // P($_FILES["file"]["tmp_name"], false);
        // P(Yii::$app->basePath . '/web/' . Yii::$app->params['uploadPath'].$filePath . $fileName);
        $path = Yii::$app->basePath . '/web/uploads/'.$filePath;//存放的路径（不包含文件名）
        if(!file_exists($path)){//创建今天日期的文件夹
            mkdir($path, 0777, true);
            chmod($path, 0777);
        }

        if(move_uploaded_file($_FILES["file"]["tmp_name"], Yii::$app->basePath . '/web/uploads/'.$filePath . $fileName)){
            // echo SITE_PATH. Yii::$app->params['uploadPath'] . $filePath . $fileName;
            return Tools::showRes(0,'success',[
                'url' => '/web/uploads/'.$filePath. $fileName,
            ]);
        }else{
            echo '';
        }
    }





    /*
返回客户端函数
$args = array(
    '0'  返回码
    '1'  返回信息
)
$data  返回数据，一般为数组，比如获取信息列表信息的时候
$url   返回链接，跳转链接，比如微信登录的时候
*/
    public static function showRes($args = [0, '操作成功'], $data = '', $url = '')
    {
        $res = array(
            'code' => $args[0],
            'info' => $args[1]
        );
        if(!empty($data)){
            $res['data'] = $data;
        }

        if(!empty($url)){
            $res['url'] = $url;
        }
        // return json_encode($res, JSON_UNESCAPED_UNICODE); 中文 生效
        return $res;//JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES = 320  中文/ 同时生效
    }
}